package com.zhixinhuixue.zsyte.xxx.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView.OnEditorActionListener
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.scandecode.ScanDecode
import com.scandecode.inf.ScanInterface
import com.scandecode.inf.ScanInterface.OnScanListener
import com.zhixinhuixue.zsyte.xxx.R
import com.zhixinhuixue.zsyte.xxx.app.api.NetUrl
import com.zhixinhuixue.zsyte.xxx.app.base.BaseActivity
import com.zhixinhuixue.zsyte.xxx.app.ext.initBack
import com.zhixinhuixue.zsyte.xxx.databinding.ActivitySmtBinding
import com.zhixinhuixue.zsyte.xxx.ui.adapter.WLPBAdapter
import com.zhixinhuixue.zsyte.xxx.ui.viewmodel.SMTViewModel
import me.hgj.mvvmhelper.ext.*
import me.hgj.mvvmhelper.net.LoadStatusEntity
import me.hgj.mvvmhelper.net.LoadingDialogEntity
import java.util.*


/**
 * 作者　: hegaojian
 * 时间　: 2020/11/18
 * 描述　: 虽然在Activity代码少了，但是DataBinding 不太好用
 */
class SMTActivity : BaseActivity<SMTViewModel, ActivitySmtBinding>() {
    private var mRelationship: MutableList<String> = ArrayList()
    private var mDeliveryLabelsItems: MutableList<String> = ArrayList()
    private var mNames: MutableList<String> = ArrayList()
    private var scanDecode: ScanInterface? = null
    private val testAdapter: WLPBAdapter by lazy { WLPBAdapter() }

    private val mType: Int by lazy { intent.getIntExtra("type", 0) }
    override fun initView(savedInstanceState: Bundle?) {
        //初始化toolbar
        mToolbar.initBack(if (mType == 1) "SMT上料" else "SMT核料") {
            finish()
        }

        mViewModel.getWorkOrdersSheet()


        initScanner()

        mDataBind.edtZwh.setOnEditorActionListener(OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE || event != null && event.keyCode === KeyEvent.KEYCODE_ENTER) {
               postData()
                true
            } else false
        })
    }

    private fun initScanner() {
        try {
            scanDecode = ScanDecode(this)
            scanDecode?.initService("true")
            scanDecode?.getBarCode(object : OnScanListener {
                override fun getBarcode(data: String) {
                    if (TextUtils.isEmpty(mDataBind.tvGdxz.text.toString())) {
                        "请先选择工单".toast()
                        return
                    }
                    if (!TextUtils.isEmpty(data)) {
                        when {
                            TextUtils.isEmpty(mDataBind.edtLpb.text.toString()) -> {
                                mDataBind.edtLpb.setText(data)
                                mDataBind.edtFdxz.requestFocus()
                                return
                            }
                            TextUtils.isEmpty(mDataBind.edtFdxz.text.toString()) -> {
                                mDataBind.edtFdxz.setText(data)
                                mDataBind.edtZwh.requestFocus()
                                return
                            }
                            TextUtils.isEmpty(mDataBind.edtFdxz.text.toString()) -> {
                                mDataBind.edtZwh.setText(data)
                                mDataBind.edtLpb.clearFocus()
                                mDataBind.edtZwh.clearFocus()
                                mDataBind.edtFdxz.clearFocus()
                                return
                            }
                        }
//
//                        if (TextUtils.isEmpty(mDataBind.edtLpb.text.toString())){
//                            mDataBind.edtLpb.setText(data)
//                            mDataBind.edtLpb.clearFocus()
//                            mDataBind.edtFdxz.requestFocus()
//
//                        }else {
//                            if (TextUtils.isEmpty(mDataBind.edtFdxz.text.toString())){
//                                mDataBind.edtFdxz.setText(data)
//                                mDataBind.edtFdxz.clearFocus()
//                                mDataBind.edtZwh.requestFocus()
//
//                            }else{
//                                if (TextUtils.isEmpty(mDataBind.edtZwh.text.toString())){
//                                    mDataBind.edtZwh.setText(data)
//                                    mDataBind.edtZwh.clearFocus()
//                                }
//                            }
//                        }
//


                    } else {

                    }
                }

                override fun getBarcodeByte(bytes: ByteArray) {}
            })
        } catch (e: Exception) {

        }


    }


    /**
     * 请求成功
     */
    override fun onRequestSuccess() {
        //监听登录结果
        mViewModel.sheetData.observe(this, {
            it.forEach { item ->
                mRelationship.add(item.Name)
            }
        })



        mViewModel.commitData.observe(this, {
            runOnUiThread {
                mDataBind.tvSuccess.visible()
                mDataBind.tvError.gone()
//                mDataBind.tvGdxz.setText("")
                mDataBind.edtLpb.setText("")
                mDataBind.edtZwh.setText("")
                mDataBind.edtFdxz.setText("")
                mDataBind.edtLpb.clearFocus()
                mDataBind.edtZwh.clearFocus()
                mDataBind.edtFdxz.clearFocus()
                mDataBind.edtLpb.tag = null
            }
        })


    }

    /**
     * 请求失败
     * @param loadStatus LoadStatusEntity
     */
    override fun onRequestError(loadStatus: LoadStatusEntity) {
        when (loadStatus.requestCode) {
            NetUrl.GET_WORKORDERSSHEET -> {
                showDialogMessage(loadStatus.errorMessage)
            }

            NetUrl.Feeding_Add -> {
                mDataBind.tvSuccess.gone()
                mDataBind.tvError.visible()
                mDataBind.tvError.text = loadStatus.errorMessage
//                mDataBind.tvGdxz.setText("")
                mDataBind.edtLpb.setText("")
                mDataBind.edtZwh.setText("")
                mDataBind.edtFdxz.setText("")
                mDataBind.edtLpb.clearFocus()
                mDataBind.edtZwh.clearFocus()
                mDataBind.edtFdxz.clearFocus()
                mDataBind.edtLpb.tag = null
            }

            NetUrl.Feeding_Check -> {
                mDataBind.tvSuccess.gone()
                mDataBind.tvError.visible()
                mDataBind.tvError.text = loadStatus.errorMessage
                mDataBind.tvGdxz.setText("")
                mDataBind.edtLpb.setText("")
                mDataBind.edtZwh.setText("")
                mDataBind.edtFdxz.setText("")
                mDataBind.edtLpb.clearFocus()
                mDataBind.edtZwh.clearFocus()
                mDataBind.edtFdxz.clearFocus()
                mDataBind.edtLpb.tag = null
            }
        }
    }

    inner class LoginClickProxy {

    }

    override fun showCustomLoading(setting: LoadingDialogEntity) {
        if (setting.requestCode == NetUrl.LOGIN) {
            //可以根据不同的code 做不同的loading处理
            showLoadingUi()
        }
    }

    override fun dismissCustomLoading(setting: LoadingDialogEntity) {
        if (setting.requestCode == NetUrl.LOGIN) {
            //可以根据不同的code 做不同的loading处理
            showSuccessUi()
        }
    }

    override fun onDestroy() {

        try {
            scanDecode!!.stopScan()
            scanDecode!!.onDestroy()

        } catch (e: Exception) {

        }
        super.onDestroy()
    }

    private fun initNoLinkOptionsPicker() { // 不联动的多级选项
        val pvNoLinkOptions =
            OptionsPickerBuilder(
                this
            ) { options1, options2, options3, v ->
                mDataBind.tvGdxz.setText(
                    mRelationship.get(options1)
                )
                mDataBind.tvGdxz.tag = mViewModel.sheetData.value!![options1].Id
                mDataBind.edtLpb.requestFocus()
            }
                .setOptionsSelectChangeListener { options1, options2, options3 -> }
                .setItemVisibleCount(5)
                .setSubmitText("确定") //确定按钮文字
                .setCancelText("取消") //取消按钮文字
                .setSubCalSize(18) //确定和取消文字大小
                .setTitleSize(20) //标题文字大小
                .setLineSpacingMultiplier(3f)
                .setTitleColor(Color.BLACK) //标题文字颜色
                .setSubmitColor(-0xc17c07) //确定按钮文字颜色
                .setCancelColor(-0x838282) //取消按钮文字颜色
                .setTitleBgColor(Color.WHITE) //标题背景颜色 Night mode
                .setBgColor(Color.WHITE) //滚轮背景颜色 Night mode
                .setContentTextSize(18) //滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label
                .build<Any>()
        pvNoLinkOptions.setPicker(mRelationship as List<Any>?)
        pvNoLinkOptions.setSelectOptions(0, 1, 1)
        pvNoLinkOptions.show()
    }


    override fun onBindViewClick() {
        setOnclickNoRepeat(mDataBind.tvGdxz, mDataBind.tvLogin) {
            when (it.id) {
                R.id.tv_gdxz -> {
                    initNoLinkOptionsPicker()
                }


                R.id.tv_login -> {
                    postData()
                }

            }
        }
    }

    private fun postData(){
        when {
            mDataBind.tvGdxz.text.toString().isEmpty() -> showErrorMsg("请选择工单")
            mDataBind.edtLpb.text.toString().isEmpty() -> showErrorMsg("料盘标不能为空")
            mDataBind.edtFdxz.text.toString().isEmpty() -> showErrorMsg("飞达选择不能为空")
            mDataBind.edtZwh.text.toString().isEmpty() -> showErrorMsg("站位号不能为空")
            else -> {
                if (mType == 1) {
                    mViewModel.addPicking(
                        mDataBind.tvGdxz.tag as String,
                        mDataBind.edtFdxz.text.toString(),
                        mDataBind.edtLpb.text.toString(),
                        mDataBind.edtZwh.text.toString()
                    )
                } else if (mType == 2) {
                    mViewModel.checkPicking(
                        mDataBind.tvGdxz.tag as String,
                        mDataBind.edtFdxz.text.toString(),
                        mDataBind.edtLpb.text.toString(),
                        mDataBind.edtZwh.text.toString()
                    )
                }
            }
        }

    }

    fun showErrorMsg(msg:String){
        mDataBind.tvSuccess.gone()
        mDataBind.tvError.visible()
        mDataBind.tvError.text = msg
    }


}